import os
import json
import traceback

from flask import Flask, jsonify
from flask import request, render_template
from werkzeug.exceptions import HTTPException

app = Flask(__name__, template_folder="html")
app.config['DEBUG'] = True

@app.before_request
def check_headers_length():
    # 检查头部字段长度
    for header, value in request.headers.items():
        if len(value) > 1000:
            raise HTTPException(description=f"Header '{header}' exceeds the maximum length of 1000 characters.")

# 处理所有HTTP异常
@app.errorhandler(HTTPException)
def handle_http_exception(error):
    return render_template('error.html', error=error), error.code

# 404错误处理
@app.errorhandler(404)
def not_found_error(error):
    return render_template('404.html'), 200

# 500错误处理
@app.errorhandler(500)
def internal_error(error):
    # 获取错误的堆栈跟踪信息
    error_traceback = ''.join(traceback.format_exception(type(error), error, error.__traceback__))
    
    return render_template('500.html', error=error, error_traceback=error_traceback), 200

# 处理所有未捕获的异常
@app.errorhandler(Exception)
def handle_exception(error):
    # 获取错误的堆栈跟踪信息
    error_traceback = ''.join(traceback.format_exception(type(error), error, error.__traceback__))
    
    return render_template('500.html', error=error, error_traceback=error_traceback), 200

@app.route("/", methods=['GET', 'POST'])
def default():
    return render_template("index.html")

@app.route("/<page_name>.html")
def page(page_name):
    return render_template(f"{page_name}.html")


if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8001, debug=True)